import 'dart:io';

import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:oktoast/oktoast.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'package:provider/provider.dart';
import 'package:sjx/pages/task/submit/detail/task_submit_detail_vm.dart';


class TaskSubmitDetailPage extends StatefulWidget {
  final String taskNo;
  final String orderNo;
  final VoidCallback? onSubmitted;

  const TaskSubmitDetailPage({
    Key? key,
    required this.taskNo,
    required this.orderNo,
    this.onSubmitted,
  }) : super(key: key);

  @override
  _TaskSubmitDetailPageState createState() => _TaskSubmitDetailPageState();
}

class _TaskSubmitDetailPageState extends State<TaskSubmitDetailPage> {
  final TextEditingController _commentController = TextEditingController();
  late final TaskSubmitDetailViewModel _viewModel = TaskSubmitDetailViewModel();


  @override
  void initState() {
    super.initState();
    _viewModel.setOrderNo(widget.orderNo);
    _viewModel.getTask(widget.taskNo);
  }

  Future<void> _pickImage() async {
    if (_viewModel.uploadedImages.length >= 3) {
      showToast('最多只能上传3张图片');
      return;
    }

    try {
      final List<XFile>? pickedFiles = await ImagePicker().pickMultiImage(
        maxWidth: 1024,
        maxHeight: 1024,
        imageQuality: 80,
      );

      if (pickedFiles != null && pickedFiles.isNotEmpty) {
        setState(() {
          int remainingSlots = 3 - _viewModel.uploadedImages.length;
          int filesToAdd = pickedFiles.length > remainingSlots
              ? remainingSlots
              : pickedFiles.length;

          for (int i = 0; i < filesToAdd; i++) {
            _viewModel.uploadedImages.add(File(pickedFiles[i].path));
          }

          if (pickedFiles.length > remainingSlots) {
            showToast('已添加$remainingSlots张图片，最多3张');
          }
        });
      }
    } catch (e) {
      showToast('图片选择错误: ${e.toString()}');
    }
  }

  Future<void> _removeImage(int index) async {
    _viewModel.uploadedImages.removeAt(index);
  }


  void _previewImage(List<String> images, int initialIndex) {
    showDialog(
      context: context,
      builder: (context) => Dialog(
        child: SizedBox(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height * 0.7,
          child: PageView.builder(
            itemCount: images.length,
            controller: PageController(initialPage: initialIndex),
            itemBuilder: (context, index) {
              return InteractiveViewer(
                child: CachedNetworkImage(
                  imageUrl: images[index],
                  fit: BoxFit.contain,
                ),
              );
            },
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context){
        return _viewModel;
      },
      child:  Consumer<TaskSubmitDetailViewModel>(builder: (context, value, child){
        if(value.isLoading) {
          return Center(child: CircularProgressIndicator());
        }
        return Scaffold(
          appBar: AppBar(
            title: const Text('提交任务结果'),
            centerTitle: true,
          ),
          body: Column(
            children: [
              Expanded(
                child: SingleChildScrollView(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 任务要求部分
                      _buildRequirementSection(),
                      const SizedBox(height: 24),

                      // 上传图片部分
                      _buildUploadSection(),
                      const SizedBox(height: 24),

                      // 备注部分
                      _buildCommentSection(),
                    ],
                  ),
                ),
              ),
            ],
          ),
        );
      }),
    );

  }

  Widget _buildRequirementSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '需提交内容',
          style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
        ),
        const SizedBox(height: 12),
        Text(
          _viewModel.taskDetailModel!.taskRequirement,
          style: const TextStyle(fontSize: 15, height: 1.5),
        ),
        if (_viewModel.taskDetailModel!.taskRequirementImages.isNotEmpty) ...[
          const SizedBox(height: 12),
          SizedBox(
            height: 100,
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: _viewModel.taskDetailModel!.taskRequirementImages.length,
              itemBuilder: (context, index) {
                return GestureDetector(
                  onTap: () => _previewImage(_viewModel.taskDetailModel!.taskRequirementImages, index),
                  child: Padding(
                    padding: EdgeInsets.only(right: 8),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: CachedNetworkImage(
                        imageUrl: _viewModel.taskDetailModel!.taskRequirementImages[index],
                        width: 100,
                        height: 100,
                        fit: BoxFit.cover,
                        placeholder: (context, url) => Container(
                          color: Colors.grey[200],
                          child: const Center(child: CircularProgressIndicator()),
                        ),
                        errorWidget: (context, url, error) => Container(
                          color: Colors.grey[200],
                          child: const Icon(Icons.error),
                        ),
                      ),
                    ),
                  ),
                );
              },
            ),
          ),
        ],
      ],
    );
  }

  Widget _buildUploadSection() {
    final images = _viewModel.taskSubmitModel?.images ?? [];
    final hasImages = images.isNotEmpty;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '已上传任务结果截图',
          style: TextStyle(
            fontSize: 16.sp,
            fontWeight: FontWeight.bold,
          ),
        ),
        SizedBox(height: 12.h),

        if (hasImages)
          SizedBox(
            height: 120.h,
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: images.length,
              itemBuilder: (context, imgIndex) {
                return GestureDetector(
                  onTap: () {
                    _showImagePreview(context, images, imgIndex);
                  },
                  child: Padding(
                    padding: EdgeInsets.only(top: 8.h, right: 8.w),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(8.r),
                      child: CachedNetworkImage(
                        imageUrl: images[imgIndex],
                        height: 120.h,
                        width: 120.h,
                        fit: BoxFit.cover,
                        errorWidget: (context, url, error) {
                          return Image.asset(
                            'assets/images/error_image_load.png',
                            width: 120.h,
                            height: 120.h,
                            fit: BoxFit.cover,
                          );
                        },
                      ),
                    ),
                  ),
                );
              },
            ),
          )
        else
          Container(
            width: double.infinity,
            padding: EdgeInsets.symmetric(vertical: 24.h, horizontal: 16.w),
            decoration: BoxDecoration(
              color: Colors.grey[100],
              borderRadius: BorderRadius.circular(8.r),
              border: Border.all(color: Colors.grey[300]!),
            ),
            child: Column(
              children: [
                Icon(
                  Icons.image_not_supported_outlined,
                  size: 32.sp,
                  color: Colors.grey[500],
                ),
                SizedBox(height: 8.h),
                Text(
                  '未上传图片',
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),
          ),
      ],
    );
  }

  void _showImagePreview(BuildContext context, List<String> images, int initialIndex) {
    showDialog(
      context: context,
      builder: (context) => Dialog(
        backgroundColor: Colors.transparent,
        insetPadding: EdgeInsets.zero,
        child: SizedBox(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height * 0.8,
          child: PhotoViewGallery.builder(
            itemCount: images.length,
            builder: (context, index) {
              return PhotoViewGalleryPageOptions(
                imageProvider: CachedNetworkImageProvider(images[index]),
                minScale: PhotoViewComputedScale.contained,
                maxScale: PhotoViewComputedScale.covered * 2,
                initialScale: PhotoViewComputedScale.contained,
              );
            },
            backgroundDecoration: const BoxDecoration(color: Colors.black),
            pageController: PageController(initialPage: initialIndex),
            enableRotation: true,  // 允许旋转
            loadingBuilder: (context, event) => Center(
              child: CircularProgressIndicator(
                value: event == null ? 0 : event.cumulativeBytesLoaded / event.expectedTotalBytes!,
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildCommentSection() {
    final comment = _viewModel.taskSubmitModel?.comment ?? '';
    final hasComment = comment.isNotEmpty;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '已提交备注内容',
          style: TextStyle(
            fontSize: 16.sp,
            fontWeight: FontWeight.bold,
          ),
        ),
        SizedBox(height: 12.h),
        Container(
          padding: EdgeInsets.all(12.w),
          decoration: BoxDecoration(
            color: Colors.grey[100],
            borderRadius: BorderRadius.circular(8.r),
            border: Border.all(color: Colors.grey[300]!),
          ),
          child: hasComment
              ? Text(
            comment,
            style: TextStyle(
              fontSize: 15.sp,
              height: 1.5,
            ),
          )
              : Row(
            children: [
              Icon(
                Icons.short_text_outlined,
                size: 16.sp,
                color: Colors.grey[500],
              ),
              SizedBox(width: 8.w),
              Text(
                '未填写任何内容',
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.grey[600],
                  fontStyle: FontStyle.italic,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }
}